//
//  AIDiaryReplayBean.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/11.
//
/**
 * 来信 - 豆包
 */
import Foundation
import SwiftUI
class AIWeeklyLetterBean : Identifiable ,Codable {
    
    var max_tokens: Int64 = configManager.getConfig().AiConfig.maxTokens ?? 1024
    var temperature: Float64 = configManager.getConfig().AiConfig.temperature ?? 0.9
    var top_p: Float64 = configManager.getConfig().AiConfig.top_p ?? 0.95
    var stream = false
    var messages: [MessagesV2]
    var model :String
    
    
    init(model: String?, content : String, time: TimeInterval, botRoleBean: RoleBean, reissueLetter: ReissueLetterBean?) {
        self.model = model ?? ""
        let userRoleBean = RoleBean.get(userManager.user, botRoleBean)
        self.messages = AIWeeklyLetterBean.getMessagesList(content: content, time: time, botRoleBean: botRoleBean, userRoleBean: userRoleBean, reissueLetter: reissueLetter)
    }
    
    private static func getMessagesList(content : String, time: TimeInterval, botRoleBean: RoleBean,
                                        userRoleBean: RoleBean, reissueLetter: ReissueLetterBean?) ->[MessagesV2] {
        //动作描述
        let headDesc = configManager.getConfig().getAiDescribe().headDescribe ?? ""
        let botDesc =  RoleBean.getBotDesc(botRoleBean)
        let userDesc =  RoleBean.getUserDesc(botRoleBean)
        let memoryDesc = AppStorageManager.shared.toggleMemoryInject ? configManager.getConfig().getAiDescribe().aiMemoryInjectDesc?.formatAiChatContent(ActiveAIMemoryExt.instance.getAiMemoryStr(botRoleBean: botRoleBean)) ?? "" : ""
        var letterDescribe = configManager.getConfig().getAiDescribe().letterDescribe ?? ""
        //如果letterDescribe 人设，则使用里面的人设，主要用于一些特定的活动
        if ((reissueLetter?.desc ?? "").isEmpty == false) {
            letterDescribe = reissueLetter?.desc ?? ""
        }
        let ruleDesc = "\(headDesc)\(letterDescribe)"
        let enDesc = configManager.getConfig().getAiDescribe().enDesc ?? ""
        let desc = "\(botDesc)\n\n---\n\(userDesc)\(memoryDesc)\(enDesc)"
        
        var listMsg : [MessagesV2] = []
        listMsg.append(MessagesV2("system", botRoleBean.name ?? "", desc.formatAiChat(botRoleBean,time)))
        
        let read = reissueLetter?.read ?? true //是否读取日记

        let content = content.isEmpty || !read ? ruleDesc : "以下是我上一周的日记中，比较重要的一部分:‘\(content)’请根据我的日记内容，\(ruleDesc)"
        
        listMsg.append(MessagesV2("user", userRoleBean.name ?? "", content.formatAiChat(botRoleBean,time)))
        
        return listMsg
    }
    
    
}
